package com.ncucoder.soms.controller;

import com.ncucoder.soms.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 文件上传/下载控制类
 *
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-11
 **/
@RestController
@RequestMapping("/file")
public class FileController {

    private Logger logger = LoggerFactory.getLogger(FileController.class);

    @PostMapping
    public void upload(@RequestParam MultipartFile file, HttpServletResponse response) {
        if (file != null) {
            String filename = FileUtils.upload(file);
            if (filename != null) {
                logger.info("上传成功: " + filename);
                return;
            }
        }
        response.setStatus(500);
        logger.error("上传失败");
    }

    @GetMapping("/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) {
        logger.info("尝试下载: " + filename);

        filename = new String(Base64.getDecoder().decode(filename), StandardCharsets.UTF_8);

        logger.info("尝试下载: " + filename);

        File file = FileUtils.isExisted(filename);
        if (file != null) {
            response.addHeader("Content-Disposition", "attachment; filename=" + filename);
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                byte[] buffer = new byte[1024];
                bis = new BufferedInputStream(new FileInputStream(file));
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                logger.info("下载成功: " + filename);

            } catch (IOException e) {
                response.setStatus(500);
                logger.error(e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                    }
                }

                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                    }
                }

            }
        } else {
            logger.info("文件不存在");
            response.setStatus(404);
        }


    }
}
